package com.kasax.basiclib;

import android.app.Application;
import android.util.Log;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

public class ModuleInitHelper {
    private static AtomicBoolean initialized = new AtomicBoolean();
    private static final CopyOnWriteArrayList<IModuleAppInit> moduleInitsCache = new CopyOnWriteArrayList<>();

    public static void invokeModuleInits(String applicationClsName) {
        Log.e(AppConstants.LOG_TAG, "ModuleInitHelper invokeModuleInits applicationClsName: " + applicationClsName);
        if (initialized.get()) {
            return;
        }

        try {
            // 使用反射或ServiceLoader机制发现所有实现类
            discoverModuleInits();
            Application application = getApplication();
            Log.e(AppConstants.LOG_TAG, "ModuleInitHelper invokeModuleInits application: " + application);
            for (IModuleAppInit iModuleAppInit : moduleInitsCache) {
                Log.e(AppConstants.LOG_TAG, "ModuleInitHelper 初始化 : " + iModuleAppInit.getClass().getName());
                iModuleAppInit.init(application);
            }
            initialized.compareAndSet(false, true);
        } catch (Exception e) {
            Log.d(AppConstants.LOG_TAG, "ModuleInitHelper Filed to initialize modules", e);
        }
    }

    private static Application getApplication() {
        // 获取Application实例
        try {
            Class activityThread = Class.forName("android.app.ActivityThread");
            Object currentActivityThread = activityThread.getMethod("currentActivityThread").invoke(null);
            Object app = activityThread.getMethod("getApplication").invoke(currentActivityThread);
            return (Application) app;
        } catch (Exception e) {
            Log.d(AppConstants.LOG_TAG, "ModuleInitHelper getApplication error:" + e.getMessage());
        }
        return null;
    }

    private static void discoverModuleInits() {
        Log.e(AppConstants.LOG_TAG, "ModuleInitHelper discoverModuleInits : ");
        // 使用反射机制发现实现类
        try {
            for (Class<IModuleAppInit> appInitClass : ClassUtils.getAllClassByInterface(IModuleAppInit.class)) {
                if (appInitClass != null) {
                    try {
                        IModuleAppInit moduleAppInit = (IModuleAppInit) appInitClass.newInstance();
                        Log.e(AppConstants.LOG_TAG, "ModuleInitHelper discoverModuleInits  cache:  " + moduleAppInit.getClass().getName());
                        moduleInitsCache.add(moduleAppInit);
                    } catch (Exception e) {
                        Log.e(AppConstants.LOG_TAG, "Failed to instantiate class: " + appInitClass.getName(), e);
                    }
                }
            }

        } catch (Exception e) {
            Log.e(AppConstants.LOG_TAG, "ModuleInitHelper discoverModuleInits error:", e);
        }
    }
}
